const path = require("path");
const defaultConfig = require("../template/webpack/webpack.config.default");
const { merge } = require("webpack-merge");
const webpack = require("webpack")
const WebpackDevServer = require("webpack-dev-server");

async function serve(args){
    // 1. 读取用户的配置文件
    const userConfig = require(path.join(process.cwd(), 'hm.config')) || {}
    // 2. 合并默认配置和用户配置
    const config = merge(defaultConfig, {
        mode:'development'
    })
    // 3. 生成webpack编译器实例
    const compiler = webpack(config)
    // 4. 创建dev server实例
    // new WebpackDevServer(配置对象，webpack实例)
    const server = new WebpackDevServer({
        static: {
            directory: path.join(process.cwd(), 'dist'),
            watch: true
        },
        hot: true,
        port: args.port,
        open: true,
        client: {
            overlay: true
        },
        ...userConfig.devServer
    }, compiler)
    // 5. 启动实例
    await server.start();
    console.log('服务已启动，请访问 http://localhost:' + args.port +'进行访问')
}

module.exports = {
    serve
}